package com.hmall.service;


import com.hdmall.business.common.common.ServerResponse;
import com.hmall.util.CastHotUtil;
import com.hdmall.business.common.util.SimilarUtil;
import com.hmall.vo.*;
import com.hmall.vo.BigList;
import com.hmall.mapper.*;
import com.hmall.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;

/**
 * @Author zhoutao
 */
@Service
public class ProductClassService {

    /**
     * 数据库中父节点11代表着锦纶
     */
//    private static final int PARENT_ID = 6;

    private static final int SUCCESS = 50;

    private  MallProductMapper mallProductMapper;

    private  MallAttrConnectMapper mallAttrConnectMapper;

    private  MallPriceMapper mallPriceMapper;

    private  MallHistoryMapper mallHistoryMapper;

    private  MallHotMapper mallHotMapper;

    private  MallOrderMapper mallOrderMapper;

    private  MallOrderItemMapper mallOrderItemMapper;

    private  SysUserRoleMapper sysUserRoleMapper;

    private  MallCommentMapper mallCommentMapper;

    private  SysDeptCustomerMapper sysDeptCustomerMapper;

    private final MobileHomeService mobileHomeService;

    @Autowired
    public ProductClassService(MallProductMapper mallProductMapper, SysDeptCustomerMapper sysDeptCustomerMapper, MallAttrConnectMapper mallAttrConnectMapper, MallPriceMapper mallPriceMapper, MallHistoryMapper mallHistoryMapper, MallHotMapper mallHotMapper, MallOrderMapper mallOrderMapper, MallOrderItemMapper mallOrderItemMapper, MallCommentMapper mallCommentMapper, SysUserRoleMapper sysUserRoleMapper, MobileHomeService mobileHomeService) {
        this.mallProductMapper = mallProductMapper;
        this.sysDeptCustomerMapper = sysDeptCustomerMapper;
        this.mallAttrConnectMapper = mallAttrConnectMapper;
        this.mallPriceMapper = mallPriceMapper;
        this.mallHistoryMapper = mallHistoryMapper;
        this.mallHotMapper = mallHotMapper;
        this.mallOrderMapper = mallOrderMapper;
        this.mallOrderItemMapper = mallOrderItemMapper;
        this.mallCommentMapper = mallCommentMapper;
        this.sysUserRoleMapper = sysUserRoleMapper;
        this.mobileHomeService = mobileHomeService;
    }

    /**
     * @Date 2018/11/9 10:57
     * @Param [user, typeName, fineAndPoreName, glossName, gradeName, singleShareName, sectionName, colorName, twistName, networkName, shopId, pageNum, pageSize]
     * @return com.hmall.common.ServerResponse<com.hmall.vo.PageVo>
     * @Description // 列出产品列表支持筛选
     */
    public ServerResponse<PageVo<ShortCompete>> listComProduct(SysUser user, String typeName, String fineAndPoreName, String glossName, String gradeName, String singleShareName, String sectionName, String colorName,
                                                               String twistName, String networkName, Integer shopId, Integer pageNum, Integer pageSize, Integer type) {

        //获得独立的纤度和孔数 进行组合查询
        String fineName = null;
        String poreName = null;

        //将纤度孔数拆开
        if (fineAndPoreName != null && fineAndPoreName.trim().length() > 2) {
            fineName = fineAndPoreName.split("/")[0];
            poreName = fineAndPoreName.split("/")[1];
            poreName = "/" + poreName;
        }

        //所查页数起始位置
        Integer pageStart = pageSize * (pageNum - 1);

        //总页数
        int total = mallProductMapper.selectCountData(typeName, fineName, poreName, glossName, gradeName, singleShareName, sectionName, colorName, twistName, networkName, shopId, type);

        //分页查询
        List<Map<String, Object>> mapList = mallProductMapper.selectByPage(typeName, fineName, poreName, glossName, gradeName, singleShareName, sectionName, colorName, twistName, networkName, shopId,  pageStart, pageSize, type);

        //重新封装对象
        List<ShortCompete> shortCompeteList = new ArrayList<>();

        for (Map<String, Object> map : mapList) {
            ShortCompete shortCompete = new ShortCompete();

            //拼接到最后
            //属性
            int productId = (int) map.get("productId");
            String grade = (String) map.get("grade");

            //IOS
            String name = (String) map.get("name");
            name = name +  grade + ",";
            BigDecimal price = (BigDecimal) map.get("price");
            int isNew = (int) map.get("isNew");
            String shopName = (String) map.get("shopName");
            String img = ((String) map.get("img")).split(",")[0];

            //装箱
            shortCompete.setProductId(productId);
            shortCompete.setName(name);
            shortCompete.setGrade(grade);
            shortCompete.setImg(img);
            shortCompete.setShopName(shopName);

            //不登陆无法看到挂牌价
            if (user != null) {
                shortCompete.setPrice(price);
            } else {
                BigDecimal zeroPrice = new BigDecimal(0);
                shortCompete.setPrice(zeroPrice);
            }

            shortCompete.setUnit("千克");
            shortCompete.setNew(isNew != 0);
            //库存不从这取
            shortCompete.setStock(50000000);

            //如果资质不通过则只能看普通报价，资质通过能看所有的价格
            //资质通过状态为temp表中status为3
            //价格对应了等级
            List<MallPrice> mallPriceList;

            mallPriceList = mallPriceMapper.findPriceAndGradeList(productId, grade);

            //如果找不到价格 不录入
            if (mallPriceList == null) {
                return ServerResponse.createByStatus(22, "商品找不到价格");
            }

            //价格规则
            //1.对于前台用户来说
            //如果用户登录并且已经是资质通过状态可以展示价格
            //如果用户只是登录可以通过price字段获取推荐价格
            //如果用户没登陆 什么价格都不展示

            //2.对于后台办事处人员
            //所有都能看
            //通过deptId作区分
            shortCompete.setComPrice(new ArrayList<>());
            if (user != null) {

                if (user.getDeptId() == null) {
                    SysUserRole userRole = sysUserRoleMapper.selectRole(user.getUserId());
                    int role = userRole.getRoleId();
                    //role 为2 普通用户 role为3 资质通过后的用户

                    if (role == 2) {
                        for (MallPrice mallPrice : mallPriceList) {
                            mallPrice.setPriceNum(new BigDecimal(0));
                        }
                    }
                } else {
                    for (MallPrice mallPrice : mallPriceList) {
                        mallPrice.setPriceNum(new BigDecimal(0));
                    }

                }
            }
            shortCompete.setComPrice(mallPriceList);
            shortCompeteList.add(shortCompete);
        }

        PageVo<ShortCompete> pageVo = new PageVo<>(pageNum, pageSize, total, shortCompeteList);
        return ServerResponse.createBySuccess(pageVo);
    }


    /**
     * @Date 2018/11/9 11:07
     * @Param [typeName, shopId]
     * @return com.hmall.common.ServerResponse<com.hmall.vo.BigList>
     * @Description // 写死的，所有根据这个DTY/FDY/HOY来获得列表
     */
    public ServerResponse<BigList> listBigList(HttpServletRequest request, String typeName, Integer shopId, Integer type) {

        //2018/12/21 统计PV
        mobileHomeService.recordBiUserAnaysis(request);

        //所有类型
        //所有纤度和孔数, 光泽, 单合股，捻向，截面，颜色，网络
        List<String> typeList, fineAndPoreList, glossList, singleShareList, twistList, sectionList, colorList, networkList ;

        typeList = mallProductMapper.listType(shopId);
        fineAndPoreList = mallProductMapper.listFineAndPore(typeName, shopId);
        glossList = mallProductMapper.listGloss(typeName, shopId);

        //将type在产品表里取查询得到所有的product_id 然后去price表里面查出等级
        List<Integer> productIdList = mallProductMapper.listProductIdByType(typeName, shopId);

        //单合股
        singleShareList = mallProductMapper.listSingleShare(typeName, shopId);

        //捻向
        twistList = mallProductMapper.listTwist(typeName, shopId);

        //截面
        sectionList = mallProductMapper.listSection(typeName, shopId);

        //颜色
        colorList = mallProductMapper.listColorList(typeName, shopId);

        //网络
        networkList = mallProductMapper.listNetworkList(typeName, shopId);

        List<String> gradeByIdList = new ArrayList<>();
        Set<String> newGradeSet = new HashSet<>();
        if (productIdList.size() != 0) {
            gradeByIdList = mallPriceMapper.findGradeListByProductIdStr(productIdList);
            //2代表后端 用户只能看到AA定重 AA不定重 A B
            if(type == 1) {
                String[] arr = {"AA1不定重", "AA1定重", "AA2不定重", "AA2定重", "AA3不定重", "AA3定重", "AA5不定重", "AA5定重", "AA6不定重", "AA6定重", "AA7不定重",
                        "AA7定重"};

                for (String grade : gradeByIdList) {
                    if (grade.contains("定重")) {
                        if (grade.contains("不")) {
                            newGradeSet.add("AA不定重");
                        } else {
                            newGradeSet.add("AA定重");
                        }
                    } else {
                        newGradeSet.add(grade);
                    }
                }
                gradeByIdList.clear();
                gradeByIdList.addAll(newGradeSet);
            }
        }

        int page = 1;
        StringBuilder strFineAndPore = null;
        List<String> strFineAndPoreList = new ArrayList<>();
        for (String str : fineAndPoreList) {
            if (page == 1) {
                page = 2;
                strFineAndPore = new StringBuilder(str);
            } else {
                page = 1;
                strFineAndPore.append("/").append(str);
                strFineAndPoreList.add(strFineAndPore.toString());
                strFineAndPore = null;
            }
        }


        //排序好纤度孔数顺序

        //String 改int
        List<FineAndPore> intFineAndPoreList = new ArrayList<>();
        for (String strFineAndPoreSub : strFineAndPoreList) {
            String[] str = strFineAndPoreSub.split("/");
            int fine = Integer.valueOf(str[0]);
            int pore = Integer.valueOf(str[1]);
            intFineAndPoreList.add(new FineAndPore(fine, pore));
        }


        //对结构排序
        intFineAndPoreList.sort((o1, o2) -> {
            if (o1.getFine() == o2.getFine()) {
                return o1.getPore() - o2.getPore();
            }
            return o1.getFine() - o2.getFine();
        });

        //重新得到串
        List<String> strFineAndPoreListRe = new ArrayList<>();
        for (FineAndPore fineAndPore : intFineAndPoreList) {
            String strRe = fineAndPore.getFine() + "/" + fineAndPore.getPore();
            strFineAndPoreListRe.add(strRe);
        }
        Collections.sort(typeList);
        Collections.sort(glossList);
        Collections.sort(gradeByIdList);

        int[] arr = new int[10];
        int fineRange = 5;
        for(int i = 0; i <= fineRange; i++){
            arr[i] = 40 * i;
        }

        List<FineAndPoreVo> fineAndPoreVoList = new ArrayList<>();

        int range = 0;

        while (++range <= fineRange) {
            FineAndPoreVo fineAndPoreVo = new FineAndPoreVo();
            fineAndPoreVo.setStartLine(arr[range - 1]);
            fineAndPoreVo.setEndLine(arr[range]);

            int flag = 0;
            //遍历五次，可优化为只遍历一次
            List<String> strFineAndPoreListSon = new ArrayList<>();
            for (String strRe : strFineAndPoreListRe) {

                String[] spitStr = strRe.split("/");
                int fine = Integer.valueOf(spitStr[0]);
                if (fine > arr[range - 1] && fine < arr[range]) {
                    strFineAndPoreListSon.add(strRe);
                    flag++;
                }

                Set<String> set = new LinkedHashSet<>(strFineAndPoreListSon);
                strFineAndPoreListSon.clear();
                strFineAndPoreListSon.addAll(set);

            }

            fineAndPoreVo.setFineAndPoreList(strFineAndPoreListSon);
            if (flag == 0) {
                continue;
            }
            fineAndPoreVoList.add(fineAndPoreVo);
        }

        BigList bigList = new BigList();
        bigList.setFineAndPoreVoList(fineAndPoreVoList);
        bigList.setGlossList(glossList);
        bigList.setGradeList(gradeByIdList);
        bigList.setTypeList(typeList);
        bigList.setColorList(colorList);
        bigList.setNetworkList(networkList);
        bigList.setSectionList(sectionList);
        bigList.setSingleShareList(singleShareList);
        bigList.setTwistList(twistList);

        return ServerResponse.createBySuccess(bigList);


    }

    /**
     * @Date 2018/11/9 11:16
     * @Param [userId, productId]
     * @return com.hmall.common.ServerResponse<com.hmall.vo.ProductClassDetailVo>
     * @Description // 产品详情
     */
    public ServerResponse<ProductClassDetailVo> listProductDetail(Integer userId, Integer productId) {

        if (productId == null) {
            return ServerResponse.createByStatus(21, "找不到该产品");
        }

        String title;

        MallProduct product = mallProductMapper.selectByProductId(productId);

        if (product == null) {
            return ServerResponse.createByStatus(21, "找不到该产品");
        }

        title = product.getTitle();

        List<String> gradeList = mallPriceMapper.findGradeListByProductId(productId);
        List<String> newGradeList = new ArrayList<>();

        String[] arr = {"AA1不定重", "AA1定重", "AA2不定重", "AA2定重", "AA3不定重", "AA3定重", "AA5不定重", "AA5定重", "AA6不定重", "AA6定重", "AA7不定重",
                "AA7定重"};

        for (String grade : gradeList) {
            if (grade.contains("定重")) {
                if (grade.contains("不")) {
                    newGradeList.add("AA不定重");
                } else {
                    newGradeList.add("AA定重");
                }
            } else {
                newGradeList.add(grade);
            }
        }
        gradeList.clear();
        gradeList.addAll(newGradeList);

        gradeList = newGradeList;

        Collections.sort(gradeList);

        Map<String, List<MallPrice>> price = new LinkedHashMap<>();


        //删去了role表的功能
        Integer customerId = sysDeptCustomerMapper.selectCustomerIdByCustomerUserId(userId);



        for (String grade : gradeList) {
            GradePriceVo gradePriceVo = new GradePriceVo();
            gradePriceVo.setGrade(grade);
            List<MallPrice> mallPriceList;


            mallPriceList = mallPriceMapper.findPriceListByProductIdAndGrade(productId, grade);

            if (null == customerId) {
                for (MallPrice mallPrice : mallPriceList) {
                    BigDecimal bigDecimal = new BigDecimal(0);
                    mallPrice.setPriceNum(bigDecimal);
                }
            }
            price.put(grade, mallPriceList);

        }

        BigDecimal salesVolume = mallHotMapper.selectSalesByProductId(productId);

        String grade = mallPriceMapper.findOne0Grade(product.getId());
        MallHotVo mallHotVo = CastHotUtil.hotCast(product, salesVolume, grade);

        int commentNum = mallCommentMapper.selectCountByProduct(productId);

        Double commentRank = mallHotMapper.selectByProductId(productId).getCommentRank();

        String [] subName = mallHotVo.getDetailName().split(",", -1);
        String nName =  subName[0] + "," +  subName[1] + "," +  subName[2] + "," +  subName[3] + "dtex" + "," +  subName[4] + "f" + "," +  subName[5] + "," +  subName[6] + "," +  subName[7];
        mallHotVo.setDetailName(nName);


        ProductClassDetailVo productClassDetailVo = new ProductClassDetailVo(mallHotVo, price, title, "元/千克", commentNum, commentRank);
        List<Map<String, String>> twistAndProductIdList = mallAttrConnectMapper.selectTwistFromModel( subName[2]);
        productClassDetailVo.setTwistAndProductIdList(twistAndProductIdList);

        return ServerResponse.createBySuccess(productClassDetailVo);
    }

    public ServerResponse<List<MallHotVo>> listHotPush(Integer hotCount, Integer shopId) {

        //就10条数据
//        List<Map> mapList = mallHotMapper.listHotList(hotCount, shopId);
        List<Map> mapList = mallHotMapper.listHotListWithoutOtherGrade(hotCount, shopId);

        List<MallHotVo> mallHotVoList = new ArrayList<>();
        for (Map map : mapList) {
            MallHotVo mallHotVo = new MallHotVo();
            mallHotVo.setPrice((BigDecimal) map.get("price"));
            mallHotVo.setMainImage((String) map.get("main_image"));
            mallHotVo.setSales_volume((BigDecimal) map.get("sales_volume"));
            mallHotVo.setName((String) map.get("name"));
            mallHotVo.setId((Integer) map.get("id"));
            String grade = mallPriceMapper.selectMaxGradeByProductId(mallHotVo.getId());
            mallHotVo.setGrade(grade);
            mallHotVoList.add(mallHotVo);
        }

        return ServerResponse.createBySuccess(mallHotVoList);
    }

    /**
     * @Date 2018/11/9 11:19
     * @Param [similarCount, productId, shopId]
     * @return com.hmall.common.ServerResponse<java.util.List<com.hmall.vo.MallHotVo>>
     * @Description // 相似度 计算公式
     */
    public ServerResponse<List<MallHotVo>> listSimilarPush(Integer similarCount, Integer productId, Integer shopId) {

        //商家所有卖的产品
        List<MallProduct> sellMallProductList = mallProductMapper.selectByShopId(shopId);

        //买的商品的属性
        MallProduct buyMallProduct = mallProductMapper.selectByProductId(productId);

        if (buyMallProduct == null) {
            return ServerResponse.createByStatus(21, "找不到该商品");
        }
        String buyName = buyMallProduct.getName();

        Map<Integer, Integer> map = new HashMap<>();

        for (MallProduct mallProduct : sellMallProductList) {

            int value = SimilarUtil.similarValue(buyName, mallProduct.getName());
            map.put(mallProduct.getId(), value);
        }

        List<MallProduct> mallProductList = new ArrayList<>();

        for (int i = 1; i <= similarCount;) {
            int max = 0;
            int index = 0;
            for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
                if (entry.getValue() > max) {
                    max = entry.getValue();
                    index = entry.getKey();
                }
            }
            MallProduct mallProduct = mallProductMapper.selectByPrimaryKey(index);
            List<MallPrice> mallPrice = mallPriceMapper.checkGradeByProductId(mallProduct.getId());
            if(mallPrice != null){
                mallProductList.add(mallProductMapper.selectByPrimaryKey(index));
                i++;
            }

            map.remove(index);
        }

        //取最相似的前similarCount数目的产品
        List<MallProduct> subMallProductList = new ArrayList<>();
        for (int i = 0; i < similarCount; i++) {
            subMallProductList.add(mallProductList.get(i));
        }

        //就六个不用批量查询
        List<MallHotVo> mallHotVoList = new ArrayList<>();
        for (MallProduct mallProduct : subMallProductList) {
            BigDecimal salesVolume = mallHotMapper.selectSalesByProductId(mallProduct.getId());
//            String grade = mallPriceMapper.findOne0Grade(mallProduct.getId());
            String grade = mallPriceMapper.selectMaxGradeByProductId(mallProduct.getId());
            mallHotVoList.add(CastHotUtil.hotCast(mallProduct, salesVolume, grade));

        }

        return ServerResponse.createBySuccess(mallHotVoList);
    }

    /**
     * @Date 2018/11/9 11:19
     * @Param [userId, productId]
     * @return void
     * @Description // 记录浏览记录
     */
    public void recordView(Integer userId, Integer productId) {

        MallHistory mallHistory = new MallHistory();
        mallHistory.setUserid(userId);
        mallHistory.setProductid(productId);
        MallHistory checkMallHistory;
        checkMallHistory = mallHistoryMapper.selectByUserIdAndProductId(userId, productId);
        if (checkMallHistory == null) {
            mallHistoryMapper.myInsert(mallHistory);
        } else {
            mallHistoryMapper.myUpdate(mallHistory);
        }
    }


    public ServerResponse<String> listProductContent(Integer productId) {

        return ServerResponse.createBySuccess(mallProductMapper.selectContentById(productId));
    }

    /**
     * @Date 2018/11/9 11:20
     * @Param []
     * @return com.hmall.common.ServerResponse
     * @Description // 后
     *     台更新销量
     *     根据mall_order_item 表中的相同product_id进行相加
     */
    public ServerResponse updateSalesVolume() {

        //查询所有交易成功的订单编号 BigInt 类型的编号
        List<BigInteger> successMallOrderList = mallOrderMapper.listSuccessOrderNo(SUCCESS);

        //得到product_id 和sales_volume
        List<Map<String, Object>> mallOrderItemList = mallOrderItemMapper.listGroupByProductId(successMallOrderList);

        //存储产品id
        List<Integer> mallProductIdList = new ArrayList<>();

        for (Map<String, Object> mallOrderItem : mallOrderItemList) {
            int productId = (int) mallOrderItem.get("productId");
            mallProductIdList.add(productId);
        }
        //批量查询出要更新的销量数据库
        List<MallHot> mallHotList = mallHotMapper.batchListHot(mallProductIdList);
        for (int i = 0; i < mallProductIdList.size(); i++) {
            MallHot mallHot = mallHotList.get(i);
            mallHot.setSalesVolume(((BigDecimal) mallOrderItemList.get(i).get("sumQuantity")));
            mallHotList.set(i, mallHot);
            mallHotMapper.updateHot(mallHot);
        }
        return ServerResponse.createBySuccess();
    }

    public ServerResponse cancelOrder(Long orderNo) {

        int cancelStatus = 10;
        MallOrder mallOrder = mallOrderMapper.selectAllByOrderNo(orderNo);
        if(mallOrder.getStatus() == cancelStatus && mallOrder.getStatus1() == 0 && mallOrder.getStatus2() == 0 && mallOrder.getStatus3() == 0){
            mallOrderMapper.updateByOrderNo(0, orderNo);
            return ServerResponse.createBySuccess("取消成功");

        }else{
            return ServerResponse.createByErrorMessage("该订单业务员已经通过审核无法取消");
        }

    }
}
